#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define SIZE 1024
#define MAX_ARGC 64

char* argv[MAX_ARGC];
char pwd[SIZE];

const char* UserName()
{
    char* user = getenv("USER");
    if(user) return user;
    else return "None";
}
const char* HostName()
{
    char* hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "None";
}
const char* CurrentWorkDir()
{
    char* pwd = getenv("PWD");
    if(pwd) return pwd;
    else return "None";
}

int Interactive(char out[], int size)
{
    printf("[%s@%s %s]: ", UserName(), HostName(), CurrentWorkDir());
    fgets(out, size, stdin);//会添加'\0';
    out[strlen(out)-1] = '\0';//去掉'\n'
    return strlen(out);
}

void Split(char in[])
{
    int i = 0;
    argv[i++] = strtok(in, " ");
    while(argv[i++] = strtok(NULL, " "));
    
    if(strcmp(argv[0],"ls") == 0)
    {
        argv[i-1] = (char*)"--color";
        argv[i] = NULL;
    }
    //i = 0;
    //while(argv[i])
    //{
    //    printf("%s\n",argv[i]);
    //    i++;
    //}

}

void Execute()
{
    pid_t pid = fork();

    if(pid == 0)
    {
        execvp(argv[0],argv);
        exit(1);
    }

    int status = 0;
    pid_t rid = waitpid(pid, &status, 0);

    //if(rid == pid) lastcode = WEXITSTATUS(status);
}

int BuildInCmd()
{
    int ret = 0;
    if(strcmp(argv[0],"cd") == 0)
    {
        ret = 1;

        char* target = argv[1];
        if(target == NULL) target = getenv("HOME");

        chdir(target);
        char tmp[SIZE];
        getcwd(tmp,SIZE);//获取绝对路径
        snprintf(pwd,SIZE,"PWD=%s",tmp);
        putenv(pwd);
    }
    return ret;
}
int main()
{
    while(1)
    {
        char commandline[SIZE];
        //获取命令
        int n = Interactive(commandline, SIZE);
        if(n == 0) continue;
        //切割字符
        Split(commandline);
        //内建命令
        int ret = BuildInCmd();
        if(ret) continue;
        //执行命令
        Execute();
    }
    return 0;
}
